package com.gec.anan.customer.service.impl;

import com.gec.anan.common.constant.RedisConstant;
import com.gec.anan.common.execption.AnanException;
import com.gec.anan.common.result.Result;
import com.gec.anan.common.result.ResultCodeEnum;
import com.gec.anan.common.util.AuthContextHolder;
import com.gec.anan.customer.client.CustomerInfoFeignClient;
import com.gec.anan.customer.service.CustomerService;
import com.gec.anan.model.form.customer.UpdateWxPhoneForm;
import com.gec.anan.model.vo.customer.CustomerLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerInfoFeignClient customerInfoFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录业务处理、最后返回token
     * @param code
     * @return
     */
    @Override
    public String login(String code) {
        //1、远程调用服务，进行登录【结果】
        Result<Long> result = customerInfoFeignClient.login(code);
        //2、判断失败、抛出异常
        if(result.getCode().intValue()!=200){
            throw new AnanException(result.getCode(), result.getMessage());
        }
        //3、判断成功、获取用户信息【根据主键查询】
        Long customerId = result.getData();
        //4、用户信息非空判断
        if(customerId==null){
            throw new AnanException(ResultCodeEnum.DATA_ERROR);
        }
        //5、生成token、存儲到redis中
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(
                RedisConstant.USER_LOGIN_KEY_PREFIX+token,customerId.toString(),
                RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS
        );
        //6、返回token
        return token;
    }

    /**
     * 获取客户登录信息
     * @param customerId
     * @return
     */
    @Override
    public CustomerLoginVo getCustomerLoginInfo(Long customerId) {

        //拿用户id去获取用户信息
        Result<CustomerLoginVo> result = customerInfoFeignClient.getCustomerLoginInfo(customerId);
        //异常处理
        if (result.getCode().intValue() != 200) {
            throw new AnanException(result.getCode(), result.getMessage());
        }
        CustomerLoginVo customerLoginVo = result.getData();
        //非空判断
        if (null == customerLoginVo) {
            throw new AnanException(ResultCodeEnum.DATA_ERROR);
        }
        return customerLoginVo;
    }

    /**
     * 更新客户微信手机号码
     * @param updateWxPhoneForm
     */
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        customerInfoFeignClient.updateWxPhoneNumber(updateWxPhoneForm);
        return true;
    }


}
